// 
/**  
 * All rights Reserved, Designed By 视连时代(上海)信息科技有限公司
 * @Title:   SLImagePicker.m 
 * @Package  DShop
 * @author:  zyc     
 * @date:    2019/10/29 3:48 PM
 * @Copyright: 2019 视连时代(上海)信息科技有限公司 All rights reserved. 
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目
 */

#import "SLImagePicker.h"
//#import <MobileCoreServices/MobileCoreServices.h>
//#import "NSData+ResetImage.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>

@interface SLImagePickerManager : NSObject<UINavigationControllerDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) SLImagePickerConfig *config;
@property (nonatomic,copy) void(^resultBlock)(UIImage *);
@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

 // 先用单例，否则会被释放，，后续看看,
+ (SLImagePickerManager *) shareManager;
- (void)show;

@end

@implementation SLImagePickerManager


+ (SLImagePickerManager *) shareManager {
    static SLImagePickerManager * _sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[SLImagePickerManager alloc] init];
        
        
    });
    return _sharedManager;
}

- (void)show
{
    switch (self.config.showType) {
        case SLImagePicker_ActionSheet:
            [self showActionSheet];
            break;
            
        case SLImagePicker_Photo:
            [self loadPhotoLibrary];
            break;
            
        case SLImagePicker_Camera:
            [self loadCamera];
            break;
            
        default:
            break;
    }
    
}

- (void)showActionSheet
{
    
    VHWeakSelf
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil                                                                                     message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *CameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       VHStrongSelf
       [self loadCamera];
    }];
    UIAlertAction *PhotoAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       VHStrongSelf
       [self loadPhotoLibrary];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];

    [alertController addAction:CameraAction];
    [alertController addAction:PhotoAction];
    [alertController addAction:cancelAction];

    // 否则会被释放
//    self.alertController = alertController;
    
    UIViewController *vc = [UIWindow currentViewController];
    [vc presentViewController:alertController animated:YES completion:nil];
    
}
// 打开相册
- (void)loadPhotoLibrary
{
    
//    TZImagePickerController *tziPicker = nil;
//
//    int maxCount = self.config.maxCount;
//    if (maxCount == 0) {
//        maxCount = 1;
//    }
//    tziPicker = [[TZImagePickerController alloc] initWithMaxImagesCount:maxCount delegate:self];
//    tziPicker.allowPickingOriginalPhoto = NO;
//    tziPicker.allowPickingVideo = NO;
//    __weak typeof(tziPicker) weakTziPicker = tziPicker;
//    tziPicker.didFinishPickingPhotosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
//        if (self.resultBlock){
//
//            if (photos.count){
//                self.resultBlock(photos);
//            }else{
//                self.resultBlock(nil);
//            }
//        }
//
//        [weakTziPicker dismissViewControllerAnimated:YES completion:nil];
//    };
//
//    UIViewController *vc = [UIWindow currentViewController];
//    [vc presentViewController:tziPicker animated:YES completion:nil];
    /*
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.config.maxCount columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.preferredLanguage = @"zh-Hans";
    imagePickerVc.showSelectedIndex = YES;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (self.resultBlock){
            if (photos.count){
                self.resultBlock(photos);
            }else{
                self.resultBlock(nil);
            }
        }
    }];
    
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    [[UIWindow currentViewController] presentViewController:imagePickerVc animated:YES completion:nil];
    */
    
    
}


// 打开拍照
- (void)loadCamera
{
    // 只能是单张
    int maxCount = self.config.maxCount;
    if (maxCount == 0) {
        maxCount = 1;
    }
//    TZImagePickerController *tziPicker = [[TZImagePickerController alloc] initWithMaxImagesCount:maxCount delegate:self];
//    // 裁剪框宽高比例，eg .1.0正方型 16.0/9.0 ... ，默认0，不裁剪
//    tziPicker.clipScale = self.config.clipScale;
//    __weak typeof(tziPicker) weakTziPicker = tziPicker;
//    tziPicker.didFinishPickingPhotosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets) {
//
//           if (self.resultBlock){
//
//               if (photos.count){
//                   self.resultBlock(photos);
//               }else{
//                   self.resultBlock(nil);
//               }
//           }
//
//           [weakTziPicker dismissViewControllerAnimated:YES completion:nil];
//       };
//
//       UIViewController *vc = [UIWindow currentViewController];
//       [vc presentViewController:tziPicker animated:YES completion:nil];
    
    [self takePhoto];
}

- (void)takePhoto
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
        // 无相机权限 做一个友好的提示
        VHWeakSelf
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机"                                                                                     message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           VHStrongSelf
                   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertController addAction:setAction];
        [alertController addAction:cancelAction];

        // 否则会被释放
        //    self.alertController = alertController;
            
        UIViewController *vc = [UIWindow currentViewController];
        [vc presentViewController:alertController animated:YES completion:nil];
        
//        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
//        [alert show];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self takePhoto];
                });
            }
        }];
        // 拍照之前还需要检查相册权限
    } else if ([PHPhotoLibrary authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        VHWeakSelf
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法访问相册"                                                                                     message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *setAction = [UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           VHStrongSelf
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertController addAction:setAction];
        [alertController addAction:cancelAction];

        // 否则会被释放
        //    self.alertController = alertController;
            
        UIViewController *vc = [UIWindow currentViewController];
        [vc presentViewController:alertController animated:YES completion:nil];
        
//        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
//        [alert show];
    } else if ([PHPhotoLibrary authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        NSMutableArray *mediaTypes = [NSMutableArray array];
        [mediaTypes addObject:(NSString *)kUTTypeImage];
        if (mediaTypes.count) {
            _imagePickerVc.mediaTypes = mediaTypes;
        }
        [[UIWindow currentViewController] presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = [UIWindow currentViewController].navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = [UIWindow currentViewController].navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (@available(iOS 9, *)) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
 
    }
    return _imagePickerVc;
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    tzImagePickerVc.allowPickingOriginalPhoto = NO;
    tzImagePickerVc.allowPickingVideo = NO;
    tzImagePickerVc.preferredLanguage = @"zh-Hans";
    tzImagePickerVc.showSelectedIndex = YES;
//    tzImagePickerVc.sortAscendingByModificationDate = self.sortAscendingSwitch.isOn;
    [tzImagePickerVc showProgressHUD];
    if ([type isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        if (image){
            [MBProgressHUD showHUDAddedTo:[UIWindow currentViewController].view animated:YES];
//            NSData *imageData = [NSDate resetSizeOfImageData:image maxSize:300];
            NSData *imageData = [NSData resetSizeOfImageData:image compressQuality:0.2];
            [MBProgressHUD hideHUDForView:[UIWindow currentViewController].view animated:YES];
            UIImage *newImage = [UIImage imageWithData:imageData];
            self.resultBlock(@[newImage]);
        }else{
            self.resultBlock(nil);
        }
        

    }

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

-(void)dealloc
{
    NSLog(@"picker release");
}

@end


@implementation SLImagePicker

/** 调用  */
+ (void)show:(SLImagePickerConfig *)config
      result:(void(^)(NSArray <UIImage *>*imageList))result
{
    SLImagePickerManager *picker = [SLImagePickerManager shareManager];
    picker.config = ({
        SLImagePickerConfig *customConfig = [[SLImagePickerConfig alloc] init];
        customConfig.showType = SLImagePicker_ActionSheet;
        customConfig.maxCount = 1;
        if (config) {
            customConfig = config;
        }
        customConfig;
    });
    
    picker.resultBlock = [result copy];
    [picker show];
}

@end
